// pages/goods_list/index.js
import regeneratorRuntime from '../../lib/runtime/runtime';
import { request } from '../../request/index.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs:[
      {
        id:0,
        value:"综合",
        isActive:true
      },
      {
        id:2,
        value:"销量",
        isActive:false
      },
      {
        id:3,
        value:"价格",
        isActive:false
      },
    ],
    goodsList:[]
  },
  QueryParams:{
    query:'',
    cid:'',
    pagenum:1,
    pagesize:10,
  },
  // 总页数
  totalPages:1,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.QueryParams.cid = options.cid
    this.getGoodsList()
  },
  tabsItemChange(e){
    const {index} = e.detail
    let {tabs} = this.data
    tabs.forEach((v,i)=>i===index?v.isActive=true:v.isActive=false)
    this.setData({
      tabs
    })
  },
  // 获取数据
  async getGoodsList(){
    const res = await request({url:"/goods/search",data:this.QueryParams});
    // 获取接口返回的总条数
    const total = res.total
    this.totalPages = Math.ceil(total/this.QueryParams.pagesize)
    this.setData({
      goodsList:[...this.data.goodsList,...res.goods]
    })
    wx.stopPullDownRefresh();
  },
  // 上拉触底
  onReachBottom(){
    // 判断是否还有下一页数据
    if(this.QueryParams.pagenum>=this.totalPages){
      wx.showToast({title: '没有更多商品'});
    }else{
      this.QueryParams.pagenum++
      this.getGoodsList()
    }
  },
  // 下拉刷新
  onPullDownRefresh(){
    this.setData({
      // 重置数组
      goodsList:[]
    })
    // 重置页码
    this.QueryParams.pagenum=1
    // 发送请求
    this.getGoodsList()
  }
})